package com.chart.web.controller.aliPay;
import com.alipay.api.AlipayApiException;
import com.aliyun.tea.utils.StringUtils;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.QRCodeUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 测试用
 */
@Slf4j
@RestController
@RequestMapping
public class AlipayController {

    private AlipayUtil alipayUtil;


    @Autowired
    public void setAlipayUtil(AlipayUtil alipayUtil) {
        this.alipayUtil = alipayUtil;
    }

    /**
     * 支付宝当面付支付接口
     *
     * @param response
     * @param orderNum
     * @return
     */
    @GetMapping(value = "/order/alipay/text")
    @ApiOperation("付费套餐：支付宝支付主接口")
    @Transactional(rollbackFor = Exception.class) // 添加事务管理注解，捕获所有异常回滚事务
    public AjaxResult createAlipayQRCode(HttpServletResponse response, String orderNum) {
        if(StringUtils.isEmpty(orderNum)){
            log.error("支付宝支付主接口orderNum参数位空");
            return AjaxResult.error("orderNum参数为空");
        }
        OutputStream sos = null;
        try {
            if (orderNum == null || orderNum.isEmpty()) {
                return AjaxResult.error("订单号不能为空");
            }
            // 模拟订单信息
            String orderDetails = "商品描述"; // 商品描述
            Integer totalPrice = 1;        // 总金额
            String price = totalPrice.toString(); // 转换为字符串类型

            // 调用支付宝支付接口获取二维码URL
            String qrCodeUrl = alipayUtil.aliPayText(orderNum, price, orderDetails);
            if (qrCodeUrl == null) {
                return AjaxResult.error("获取二维码URL失败！");
            }
            // 设置响应内容类型为图片
            response.setContentType("image/png");
            // 获取输出流并生成二维码
            sos = response.getOutputStream();
            //生成二维码
            QRCodeUtils.encode(qrCodeUrl, sos);
            sos.flush();
            // 返回成功，二维码已经写入响应
            return AjaxResult.success();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("");
            return AjaxResult.error("二维码生成失败！");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("调用支付宝接口异常！");
        } finally {
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @GetMapping("/return")
    public String returnNotice(String out_trade_no, Model model) {
        String query = alipayUtil.query(out_trade_no);
        model.addAttribute("query", query);
        return "query";
    }

    /**
     * 支付宝当面付回调接口
     *
     * @param trade_no
     * @param total_amount
     * @param trade_status
     */
    @PostMapping("/notify")
    public void notifyUrl(String trade_no, String total_amount, String trade_status){
        System.err.println("支付宝订单编号：" + trade_no + ", 订单金额： " + total_amount + ",订单状态：" + trade_status);
    }


    /**
     * 支付宝当面付查询支付状态接口
     *
     * @param
     * @return
     * @throws AlipayApiException
     */
    @GetMapping("queryOrder")
    public AjaxResult queryOrder(String orderNum) throws AlipayApiException {
        AjaxResult queryOrder = alipayUtil.queryOrder(orderNum);
        return AjaxResult.success(queryOrder);
    }




    /**
     * 电脑网站支付
     *
     * @param response
     * @param orderNum
     * @return
     */
    @GetMapping(value = "/order/computerWebsite")
    @ApiOperation("付费套餐：支付宝支付主接口")
    @Transactional(rollbackFor = Exception.class) // 添加事务管理注解，捕获所有异常回滚事务
    public AjaxResult computerWebsite(HttpServletResponse response, String orderNum) throws AlipayApiException {
        if (orderNum == null || orderNum.isEmpty()) {
            return AjaxResult.error("订单号不能为空");
        }
        // 模拟订单信息
        String orderDetails = "商品描述"; // 商品描述
        Integer totalPrice = 1;        // 总金额
        String price = totalPrice.toString(); // 转换为字符串类型

        // 调用支付宝支付接口获取二维码URL
        String pageRedirectionData = alipayUtil.computerWebsite(orderNum, price, orderDetails);

        return AjaxResult.success(pageRedirectionData);
    }

}